
//view
function SplitTheBillRenderer(){
    var that = this;
    this.uniqueIdent = null;
    this.mainCont = null;
    
    this.mainParts = new Array();
    this.forms = new Array();
    this.idents = null;
    this.init = function(selector, uniqueIdent){
        this.uniqueIdent = '-' + uniqueIdent;
        this.setIdents();
        this.mainCont = $('<div></div>')
                        .addClass('bill-splitter-main');
        var billActionsCont = $('<div></div>')
                                .addClass('bill-actions-container')
                                .attr('id', this.idents.billActionsCont);
        var billCont = $('<div></div>')
                        .addClass('bill-container')
                        .attr('id', this.idents.billCont);
        var addItemCont = $('<div></div>')
                            .addClass('bill-add-item')
                            .attr('id', this.idents.billAddItem)
                            .attr('title', 'add a new ordered item')
                            .css('font-size', '62.5%');
        var addPersonCont = $('<div></div>')
                            .addClass('bill-add-person')
                            .attr('id', this.idents.billAddPerson)
                            .attr('title', 'add a person')
                            .css('font-size', '62.5%');
        
        addItemCont.hide();
        addPersonCont.hide();
        
        //this.makeAddItemForm(addItemCont);
        
        this.mainCont.append(billActionsCont);      
        this.mainCont.append(billCont);
        this.mainCont.append(addItemCont);
    
        $(selector).html(this.mainCont);
        
        this.setMainPart(this.idents.billActionsCont, billActionsCont);
        this.setMainPart(this.idents.billCont, billCont);
        this.setMainPart(this.idents.billAddItem, addItemCont);
        this.setMainPart(this.idents.billAddPerson, addPersonCont);
    };
    
    this.setIdents = function(){
        this.idents = {
            billsTable : 'bills-table' + this.uniqueIdent,
            
            billCont: 'bill-cont' + this.uniqueIdent,
            billActionsCont: 'bill-actions-cont' + this.uniqueIdent,
            
            billAddItem: 'bill-add-item-cont' + this.uniqueIdent,
            billAddPerson: 'bill-add-person-cont' + this.uniqueIdent,
            
            addPersonForm: {
                ident: 'bill-add-person-form' + this.uniqueIdent,
                name: 'bill-person-name' + this.uniqueIdent,
                status: 'bill-add-person-status' + this.uniqueIdent 
            },
            
            addItemForm: {
                ident: 'bill-add-item-form' + this.uniqueIdent,
                itemName: 'bill-item-name' + this.uniqueIdent,
                itemPrice: 'bill-item-price' + this.uniqueIdent,
                itemQty: 'bill-item-qty' + this.uniqueIdent
            }
        };
    };
    
    this.renderBillsArchive = function(selector, params){
        
    };
    
    this.makeAddPersonForm = function(selector, params){
        var status = $('<div></div>')
                    .attr('id', this.idents.addPersonForm.status)
                    .addClass('.add-person-form-status');
        var form = $('<form></form>')
                    .attr('id', this.idents.addPersonForm.ident)
                    .addClass('modal-form');;
        var inputStyle = 'text ui-widget-content ui-corner-all';
        var personNameLabel = $('<label></label>')
                            .attr('for', this.idents.addPersonForm.name)
                            .append('name');
        var personNameInput = $('<input></input>')
                            .attr('id', this.idents.addPersonForm.name)
                            .attr('name', this.idents.addPersonForm.name)
                            .attr('type', 'text')
                            .attr('value', '')
                            .addClass(inputStyle);
        var personSelectDiv = this.showOrderers(params.orderers);
        form.append(personNameLabel);
        form.append(personNameInput);
        form.append(personSelectDiv);
        $(selector).html(form);
        $(selector).append(status);
    };
    
    this.makeAddItemForm = function(selector, params){
        var form = $('<form></form>')
                    .attr('id', this.idents.addItemForm.ident)
                    .addClass('modal-form');
        this.forms.push();
        var inputStyle = 'text ui-widget-content ui-corner-all';
        var itemNameLabel = $('<label></label>')
                            .attr('for', this.idents.addItemForm.itemName)
                            .append('name');
        var itemNameInput = $('<input></input>')
                            .attr('id', this.idents.addItemForm.itemName)
                            .attr('name', this.idents.addItemForm.itemName)
                            .attr('type', 'text')
                            .attr('value', '')
                            .addClass(inputStyle);
                            
        var itemPriceLabel = $('<label></label>')
                            .attr('for', this.idents.addItemForm.itemPrice)
                            .append('price');
        var itemPriceInput = $('<input></input>')
                            .attr('id', this.idents.addItemForm.itemPrice)
                            .attr('name', this.idents.addItemForm.itemPrice)
                            .attr('type', 'text')
                            .attr('value', '0.00')
                            .addClass(inputStyle);
        
        var itemQtyLabel = $('<label></label>')
                            .attr('for', this.idents.addItemForm.itemQty)
                            .append('qty');
        var itemQtyInput = $('<input></input>')
                            .attr('id', this.idents.addItemForm.itemQty)
                            .attr('name', this.idents.addItemForm.itemQty)
                            .attr('type', 'text')
                            .attr('value', 1)
                            .addClass(inputStyle);
        var personSelectDiv = this.showOrderers(params.orderers);
        form.append(itemNameLabel);
        form.append(itemNameInput);
        
        form.append(itemPriceLabel);
        form.append(itemPriceInput);
        
        form.append(itemQtyLabel);
        form.append(itemQtyInput);
        form.append(personSelectDiv);   
        $(selector).html(form);

    };
    
    //shows orderers returns a div with the orderers
    this.showOrderers = function(orderers){
        var orderersCont = $('<div></div>').addClass('orderers-selection');
        var toggleSelectAllPersonsCont = $('<div></div>').addClass('add-item-add-person-cont');                    
        var personSelectDiv = $('<div></div>').addClass('add-item-add-person-cont');
        if(typeof orderers != 'undefined' && orderers != null && orderers.length > 0){
            var toggleAllAddPersonChkBoxLabel = $('<label></label>')
                                                .attr('for', 'add-all-persons-toggle')
                                                .append('select all');
            var toggleAllAddPersonChkBox = $('<input></input>')
                                            .attr('add-persons-toggle', 'yes')
                                            .attr('id', 'add-all-persons-toggle')
                                            .attr('name', 'add-all-persons-toggle')
                                            .attr('type', 'checkbox')
                                            //.attr('checked', false)
                                            .attr('value', 'yes');
            
            toggleSelectAllPersonsCont.append(toggleAllAddPersonChkBox);
            toggleSelectAllPersonsCont.append(toggleAllAddPersonChkBoxLabel);
            
            for(var i=0;i<orderers.length;i++){
                var orderer = orderers[i];
                //order.ident;
                //orderer.name;
                
                var ordererChkBoxLabel = $('<label></label>')
                                        .attr('for', orderer.ident)
                                        .append(orderer.name);
                var ordererChkBox = $('<input></input>')
                                    .attr('add-person', 'yes')
                                    .attr('id', orderer.ident)
                                    .attr('name', orderer.ident)
                                    .attr('type', 'checkbox')
                                    //.attr('checked', false)
                                    .attr('value', orderer.ident);
                personSelectDiv.append(ordererChkBox);
                personSelectDiv.append(ordererChkBoxLabel);
                
            }
            $(toggleAllAddPersonChkBox).button();
            //$(personSelectDiv).buttonset();
            $(toggleAllAddPersonChkBox).click(function(ev){
                var selector = this.checked;
                
                $('input:checkbox[add-person="yes"]').each(function(checkBox){
                        if (selector == true) {
                            this.checked = true;
                        }else{
                            this.checked = false;
                        }
                });
            });
        }
        orderersCont.append($('<h2></h2').append('added people'));
        orderersCont.append(toggleSelectAllPersonsCont);
        orderersCont.append(personSelectDiv);
        return orderersCont;
    };
    
    this.resetAddPersonForm = function(){
        //this.makeAddPersonForm(this.getMainPart(this.idents.billAddPerson).elem, {});
    };
    
    this.resetAddItemForm = function(){
        //this.makeAddItemForm(this.getMainPart(this.idents.billAddItem).elem, {});
    };
    
    this.showAddPerson = function(params){
        $(this.getMainPart(this.idents.billAddPerson).elem).dialog({
            //autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "add": function(ev) {
                    var nameField = $('#' + that.idents.addPersonForm.name);
                    var nameFieldValue = nameField.val().trim();
                    
                    var nameValid = utils.checkRegexp(nameFieldValue, /^\s*([0-9a-zA-Z' ']+)\s*$/);
                    
                    nameValid == false? nameField.addClass('ui-state-error'):true;
                    
                    if(nameValid){
                        var values = {
                            name: nameFieldValue
                        };
                        params.add.call(params.context, values);
                        //$('#' + that.idents.addPersonForm.status).html('person added');
                    }
                    
                },
                done: function() {
                    $(that.getMainPart(that.idents.billAddPerson).elem).dialog( "close" );
                }
            },
            close: function() {
                that.resetAddItemForm();
                $('#'+that.idents.addPersonForm.ident + ' input').removeClass( "ui-state-error" );
            }
        });
    };
    
    this.showAddItem = function(params){
        $(this.getMainPart(this.idents.billAddItem).elem).dialog({
            //autoOpen: false,
            height: 400,
            width: 350,
            modal: true,
            buttons: {
                "add item": function(ev) {
                    var nameField = $('#' + that.idents.addItemForm.itemName);
                    var priceField = $('#' + that.idents.addItemForm.itemPrice);
                    var qtyField = $('#' + that.idents.addItemForm.itemQty);
                    
                    var itemNameValue = nameField.val().trim();
                    var itemPriceValue = priceField.val().trim();
                    var itemQtyValue = qtyField.val().trim();
                    
                    var nameValid = utils.checkRegexp(itemNameValue, /^\s*([0-9a-zA-Z' ']+)\s*$/);
                    var priceValid = utils.checkRegexp(itemPriceValue, /^\d+(?:\.\d{1,2})?$/);
                    var qtyValid = utils.checkRegexp(itemQtyValue, /^\d+(?:\.\d{1,2})?$/);
                    
                    nameValid == false? nameField.addClass('ui-state-error'):true;
                    priceValid == false? priceField.addClass('ui-state-error'):true;
                    qtyValid == false? qtyField.addClass('ui-state-error'):true;
                    
                    if(nameValid && priceValid && qtyValid){
                        var values = {
                            name: itemNameValue,
                            price: itemPriceValue,
                            qty: itemQtyValue
                        };
                        params.add.call(params.context, values);
                        $(that.getMainPart(that.idents.billAddItem).elem).dialog( "close" );
                    }
                    
                },
                Cancel: function() {
                    $(that.getMainPart(that.idents.billAddItem).elem).dialog( "close" );
                }
            },
            close: function() {
                $('#'+that.idents.addItemForm.ident + ' input').removeClass( "ui-state-error" );
            }
        });

        //$(this.getMainPart(this.view.idents.billAddItem).elem).dialog();
    };
    
    this.renderBillActions = function(selector, params){
        var ul = $('<ul></ul>');
        
        for(var i=0;i<params.actions.length;i++){
            var li = $('<li></li>');
            var action = params.actions[i];
            var actionButton = $('<button></button>')
                //.append($('<span></span>').addClass("ui-icon ui-icon-plus"))
                .append(action.label)
                .bind('click', {info: action, context: params.context}, function(ev){
                $(this).parent().siblings().removeClass('active');
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
                $(this).parent().addClass('active');
                ev.data.info.callback.call(ev.data.context);
            }).button({
                icons: {
                    primary: "ui-icon-plus"
                }
            });
            li.append(actionButton);
            ul.append(li);
        }
        $(selector).append(ul);
    };
    
    this.renderBill = function(selector, params){
        var tableIdent = this.idents.billsTable;
        var table = $('<table></table>').attr('id', tableIdent).attr('border', '1');
        var thead = $('<thead></thead>');
        var tbody = $('<tbody></tbody>');
        var tfoot = $('<tfoot></tfoot>');
        thead.append(this.getBillHeaders(params.headers));
        
        table.append(thead);
        table.append(tbody);
        table.append(tfoot);
        //set the necessary attributte to the table
        $(selector).append(table);
        //this.setMainPart(tableIdent, table);
    };
    
    this.addBillRow = function(row){
        var tr = $('<tr></tr>').attr('id', row.ident);
        for(var i=0;i<row.rowItems.length;i++){
            var rowItem = row.rowItems[i];
            var td = $('<td></td>');
            if(typeof rowItem.ident != 'undefined' && rowItem.ident != null && rowItem.ident != ''){
                td.attr('ident', rowItem.ident);
            }
            tr.append(td.append(rowItem.content));
            var tableElem = this.getMainPart(this.idents.billsTable);
            $(tableElem).add('tbody').append(tr);
        }
        
        var actionsTd = $('<td></td>')
                        .append(
                                $('<span></span>')
                                .addClass('ui-icon ui-icon-trash float-left-fix clickable')
                                .attr('title', 'remove'))
                        .append(
                                $('<span></span>')
                                .addClass('ui-icon ui-icon-pencil float-left-fix clickable')
                                .attr('title', 'edit'));
        tr.append(actionsTd);
    };
    
    //returns the bill headers
    this.getBillHeaders = function(headersArr){
        var tr = $('<tr></tr>');
        for(var i=0;i<headersArr.length;i++){
            var header = headersArr[i];
            var headerElem = $('<th></th>').append(header.content).addClass(header.cssClass);
            tr.append(headerElem);
        }
        return tr;
    };
    
    this.renderAddPersonForm = function(selector, params){
        
    };
    
    this.setMainPart = function(ident, elem){
        removeArrItem(this.mainParts, ident);
        this.mainParts.push({
            ident: ident,
            elem: elem
        });
    };
    
    this.getMainPart = function(ident){
        return utils.getArrItem(this.mainParts, ident);
    };
    
    //this.init();
}
